#include "weatherwidget.h"
#include "utils.h"
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QJsonValue>
#include <QCompleter>
#include <QHeaderView>

static const QString apiKey = "5fd2acf50e066869c22ded5d91bbaa58"; // 替换为你的 API 密钥

WeatherWidget::WeatherWidget(QWidget *parent) : QWidget(parent), cityListModel(nullptr) {
    QVBoxLayout *mainLayout = new QVBoxLayout(this);

    // 添加标题
    QLabel *titleLabel = new QLabel(QStringLiteral("天气查询"), this);
    titleLabel->setFont(QFont(QStringLiteral("Noto Sans CJK"), 20)); // 设置字体大小
    titleLabel->setStyleSheet("color: pink;"); // 设置字体颜色为粉红色
    titleLabel->setAlignment(Qt::AlignCenter); // 设置标题居中
    mainLayout->addWidget(titleLabel);

    QHBoxLayout *inputLayout = new QHBoxLayout;
    cityComboBox = new QComboBox(this);
    cityComboBox->setFont(QFont(QStringLiteral("Noto Sans CJK"), 16)); // 增大字体
    cityComboBox->setEditable(true); // 允许编辑，以便支持模糊搜索
    cityComboBox->setInsertPolicy(QComboBox::NoInsert); // 不允许插入新项
    cityComboBox->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred); // 增加搜索框大小
    inputLayout->addWidget(cityComboBox);

    QPushButton *button = new QPushButton(QStringLiteral("查询"), this);
    button->setFont(QFont(QStringLiteral("Noto Sans CJK"), 16)); // 增大字体
    button->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Preferred); // 增加按钮大小
    inputLayout->addWidget(button);

    mainLayout->addLayout(inputLayout);

    tableWidget = new QTableWidget(this);
    tableWidget->setColumnCount(2);
    tableWidget->setFont(QFont(QStringLiteral("Noto Sans CJK"), 16)); // 设置表格字体大小
    tableWidget->setHorizontalHeaderLabels(QStringList() << QStringLiteral("字段") << QStringLiteral("值"));
    tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    tableWidget->verticalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    mainLayout->addWidget(tableWidget);

    // 设置输入框的焦点
    cityComboBox->setFocus();

    // 为 cityComboBox 安装事件过滤器
    cityComboBox->lineEdit()->installEventFilter(this);
    connect(cityComboBox->lineEdit(), &QLineEdit::editingFinished, this, [=]() {
        on_button_clicked(cityComboBox->currentText());
    });

    // 创建一个 QStringListModel 并设置数据
    cityListModel = new QStringListModel(this);

    // 设置 QComboBox 的模型
    cityComboBox->setModel(cityListModel);

    // 创建 QCompleter 并设置模型
    QCompleter *completer = new QCompleter(cityListModel, this);
    completer->setCaseSensitivity(Qt::CaseInsensitive); // 不区分大小写
    completer->popup()->setFont(QFont(QStringLiteral("Noto Sans CJK"), 16)); // 设置选项字体大小
    cityComboBox->setCompleter(completer);

    // 设置样式表美化界面
    this->setStyleSheet(R"(
        QWidget {
            background-color: #f0f0f0;
        }
        QComboBox {
            background-color: #fffacd; /* 米黄色 */
            border: 1px solid rgb(78, 41, 41);
            border-radius: 5px;
            padding: 5px;
        }
        QComboBox::drop-down {
            subcontrol-origin: padding;
            subcontrol-position: top right;
            width: 30px; /* 增加下拉按钮宽度 */
            border-left: 1px solid rgb(130, 151, 116);
            background-color: rgb(97, 141, 107); /* 绿色 */
        }
        QComboBox::down-arrow {
            content: "";
            border: 5px solid transparent;
            border-top-color: black; /* 设置箭头颜色 */
            border-width: 5px 5px 0 5px; /* 设置边框宽度 */
            width: 0;
            height: 0;
        }
        QPushButton:hover {
            background-color: #e6e6e6;
        }
        QTableWidget {
            background-color: white;
            border: 1px solid #dcdcdc;
            border-radius: 5px;
        }
        QHeaderView::section {
            background-color: #f0f0f0;
            padding: 4px;
            border: none;
            border-bottom: 1px solid #dcdcdc;
            font-size: 16px;
        }
        QComboBox QAbstractItemView {
            background-color: white;
            border: 1px solid #dcdcdc;
            border-radius: 5px;
            font-size: 20px; /* 增大模糊匹配显示框字体大小 */
        }
        QTableWidget::item {
            font-size: 20px; /* 增加结果展示部分字体大小 */
        }
    )");

    connect(button, &QPushButton::clicked, this, [=]() {
        on_button_clicked(cityComboBox->currentText());
    });

    networkManager = new QNetworkAccessManager(this);
    connect(networkManager, &QNetworkAccessManager::finished, this, &WeatherWidget::on_network_reply);

    timeoutTimer = new QTimer(this);
    timeoutTimer->setInterval(10000);
    timeoutTimer->setSingleShot(true);
    connect(timeoutTimer, &QTimer::timeout, this, &WeatherWidget::on_network_timeout);

    // 获取城市列表
    fetchCityList();
}

WeatherWidget::~WeatherWidget() {
}

bool WeatherWidget::eventFilter(QObject *watched, QEvent *event) {
    if (watched == cityComboBox->lineEdit() && event->type() == QEvent::KeyPress) {
        QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
        if (keyEvent->key() == Qt::Key_Return || keyEvent->key() == Qt::Key_Enter) {
            on_button_clicked(cityComboBox->currentText());
            return true;
        }
    }
    return QWidget::eventFilter(watched, event);
}

void WeatherWidget::fetchCityList() {
    const QString url = QStringLiteral("https://restapi.amap.com/v3/config/district?keywords=&subdistrict=2&key=%1").arg(apiKey);
    QNetworkRequest request(url);
    networkManager->get(request);
}

void WeatherWidget::on_button_clicked(const QString &city) {
    if (city.isEmpty()) {
        qDebug() << "城市名称不能为空";
        return;
    }

    const QString url = QStringLiteral("https://restapi.amap.com/v3/weather/weatherInfo?city=%1&key=%2").arg(city, apiKey);
    QNetworkRequest request(url);
    networkManager->get(request);

    // 启动超时定时器
    timeoutTimer->start();
}


void WeatherWidget::on_network_reply(QNetworkReply *reply) {
    // 取消超时定时器
    timeoutTimer->stop();

    if (reply->error() == QNetworkReply::NoError) {
        const QString response = reply->readAll();
        const QJsonDocument jsonResponse = QJsonDocument::fromJson(response.toUtf8());
        if (!jsonResponse.isNull() && jsonResponse.isObject()) {
            const QJsonObject jsonObject = jsonResponse.object();
            if (jsonObject.contains(QStringLiteral("districts"))) {
                // 解析城市列表
                QStringList cities;
                parseCityList(jsonObject[QStringLiteral("districts")].toArray(), cities);
                cityListModel->setStringList(cities);
            } else {
                const QJsonArray jsonArray = jsonObject[QStringLiteral("lives")].toArray();
                if (!jsonArray.isEmpty()) {
                    const QJsonObject live = jsonArray.first().toObject();
                    update_table(live);
                }
            }
        } else {
            qDebug() << "JSON 解析错误";
        }
    } else {
        qDebug() << "错误: " << reply->errorString();
    }

    reply->deleteLater();
}

void WeatherWidget::parseCityList(const QJsonArray &districts, QStringList &cities) {
    for (const QJsonValue &value : districts) {
        QJsonObject district = value.toObject();
        QString city = district[QStringLiteral("name")].toString();
        QString adcode = district[QStringLiteral("adcode")].toString();

        // 只保留市或更低级别的名称
        if (adcode.length() == 6 && adcode.right(2) == "00" && adcode.mid(2, 2) != "00") {
            cities.append(city);
        }

        QJsonArray subDistricts = district[QStringLiteral("districts")].toArray();
        if (!subDistricts.isEmpty()) {
            parseCityList(subDistricts, cities);
        }
    }
}

void WeatherWidget::on_network_timeout() {
    qDebug() << "错误: 网络请求超时。";
}

void WeatherWidget::update_table(const QJsonObject &live) {
    tableWidget->setRowCount(live.size());
    int row = 0;
    for (auto it = live.begin(); it != live.end(); ++it) {
        const QString key = it.key();
        QJsonValue value = it.value();
        tableWidget->setItem(row, 0, new QTableWidgetItem(fieldToChinese(key)));

        QTableWidgetItem *valueItem = new QTableWidgetItem(value.isString() ? value.toString() : value.toVariant().toString());
        
        // 如果是温度字段，并且温度超过25摄氏度，设置字体颜色为红色
        if (key == "temperature" || key == "temperature_float") {
            bool ok;
            double temperature = value.toString().toDouble(&ok);
            if (ok && temperature > 25) {
                valueItem->setForeground(Qt::red);
            }
        }

        tableWidget->setItem(row, 1, valueItem); // 显示字段值
        ++row;
    }
}

QString WeatherWidget::fieldToChinese(const QString &field) const {
    return utils::fieldToChinese(field);
}
